import asyncio
import inspect
import logging
from typing import Any, Optional, TypeVar, Callable

T = TypeVar('T')

async def resolve_awaitable(result: Any) -> Any:
    """
    递归解析所有 awaitable 对象和协程
    
    Args:
        result: 需要解析的对象
        
    Returns:
        解析后的最终结果
    """
    while inspect.iscoroutine(result) or inspect.isawaitable(result):
        try:
            result = await result
        except Exception as e:
            # 记录错误并返回适当的错误结果
            logging.error(f"Failed to resolve awaitable: {e}")
            return {
                "success": False,
                "error": f"Failed to resolve awaitable: {str(e)}"
            }
    return result

def run_in_async_context(func: Callable, *args, **kwargs) -> Any:
    """
    在异步上下文中运行同步函数
    
    Args:
        func: 需要运行的函数
        *args: 位置参数
        **kwargs: 关键字参数
        
    Returns:
        函数运行结果
    """
    if inspect.iscoroutinefunction(func):
        # 如果函数本身是协程，直接运行
        try:
            return asyncio.run(func(*args, **kwargs))
        except RuntimeError:
            # 如果事件循环已在运行，使用线程安全的方式处理
            loop = asyncio.new_event_loop()
            result = loop.run_until_complete(func(*args, **kwargs))
            loop.close()
            return result
    else:
        # 对于同步函数，使用线程池执行器
        loop = asyncio.get_event_loop()
        return loop.run_in_executor(None, lambda: func(*args, **kwargs))

class AsyncHelper:
    """异步操作辅助类"""
    
    @staticmethod
    async def safe_execute(coroutine, timeout: Optional[int] = None) -> Any:
        """
        安全地执行协程，支持超时处理
        
        Args:
            coroutine: 要执行的协程
            timeout: 超时时间（秒）
            
        Returns:
            协程执行结果
        """
        try:
            if timeout:
                return await asyncio.wait_for(coroutine, timeout=timeout)
            else:
                return await coroutine
        except asyncio.TimeoutError:
            logging.error(f"Operation timed out after {timeout} seconds")
            return {
                "success": False,
                "error": f"Operation timed out after {timeout} seconds"
            }
        except Exception as e:
            logging.error(f"Error executing coroutine: {e}")
            return {
                "success": False,
                "error": f"Error: {str(e)}"
            }
    
    @staticmethod
    def create_task(coroutine, name: Optional[str] = None) -> asyncio.Task:
        """
        创建异步任务，带有更好的错误处理
        
        Args:
            coroutine: 要执行的协程
            name: 任务名称
            
        Returns:
            创建的任务
        """
        async def task_wrapper():
            try:
                return await coroutine
            except Exception as e:
                logging.error(f"Error in task {name}: {e}")
                raise
        
        task = asyncio.create_task(task_wrapper(), name=name)
        return task

def ensure_async(func: Callable[..., T]) -> Callable[..., T]:
    """
    装饰器，确保函数以异步方式执行
    
    Args:
        func: 要装饰的函数
        
    Returns:
        装饰后的函数
    """
    def wrapper(*args, **kwargs):
        if inspect.iscoroutinefunction(func):
            return func(*args, **kwargs)
        else:
            loop = asyncio.get_event_loop()
            return loop.run_in_executor(None, lambda: func(*args, **kwargs))
    
    return wrapper

# 导出
__all__ = ["resolve_awaitable", "run_in_async_context", "AsyncHelper", "ensure_async"]